package com.haitaoit.chengquan.base;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.business.http.bean.ParamObj;
import com.haitaoit.chengquan.utils.ClickUtils;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.Loading;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.NetworkMonitor;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.lidroid.xutils.ViewUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/17.
 */

public abstract class IBaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected Activity mContext;

    protected abstract int setContentView();

    protected abstract String setTitle();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void viewOnClick(View v);

    private View mView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(setContentView());
        ViewUtils.inject(this);
        mView = getContentView(this);
        setView();
        initView();
        initData();
        initPerMission();
    }

    public View getContentView(Activity ac) {
        ViewGroup view = (ViewGroup) ac.getWindow().getDecorView();
        FrameLayout content = (FrameLayout) view.findViewById(android.R.id.content);
        return content.getChildAt(0);
    }

    private void setView() {
        if (mView.findViewById(R.id.tv_title) != null) {
            ((TextView) mView.findViewById(R.id.tv_title)).setText(setTitle());
        }
        if (mView.findViewById(R.id.iv_back) != null) {
            mView.findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if (!ClickUtils.isFastClick(v, 800)) {
            viewOnClick(v);
        }
    }

    protected void showToastS(String toast) {
        Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
    }

    protected void showToastL(String toast) {
        Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
    }

    protected void showLoading() {
        Loading.show(this);
    }

    protected void dismissLoading() {
        Loading.dismissLoading();
    }

    protected boolean hasNetWork() {
        boolean connected = NetworkMonitor.isConnected(this);
        if (!connected) {
            ToastUtils.showToast("无网络连接,请稍后再试");
        }
        return connected;
    }

    protected boolean hasNetWorkNoMsg() {
        return NetworkMonitor.isConnected(this);
    }

    protected String getSStr(View view) {
        if (view instanceof TextView) {
            return ((TextView) view).getText().toString();
        } else if (view instanceof EditText) {
            return ((EditText) view).getText().toString();
        } else {
            return "";
        }
    }

    public String GetHaveParam(List<ParamObj> paramObjs) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        for (ParamObj paramObj : paramObjs) {
            list.add(new NameValuePairSign(paramObj.getName(), paramObj.getValue()));
        }
        String sign = GetSign.genPackageSign(list);
        return sign;
    }

    private List<String> mPermissionList = new ArrayList<>();
    private String[]     permissionss     = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    private static final int MY_PERMISSIONS_MORE=2;
    private static final int MY_PERMISSIONS_ONE=1;

    //单个权限申请
    public void initListPerMission(String permission){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        MY_PERMISSIONS_ONE);
            }else {
               //TODO：已经有了权限了

            }
        }else {
            //TODO：已经有了权限了

        }
    }

    //多个权限一起申请
    public void initPerMission() {
        mPermissionList.clear();
        for (int i = 0; i < permissionss.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissionss[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissionss[i]);
            } else {
                //TODO：已经有了权限了
                chekeHavePermission(permissionss[i]);
            }
        }
        if (!mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            //请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissions, MY_PERMISSIONS_MORE);
        }else {
            //TODO：已经有了权限了

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode){

            //单个权限
            case MY_PERMISSIONS_ONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //TODO：已经有了权限了
                    chekeHavePermission(permissions[0]);
                } else {
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0]);
                    if (TextUtils.equals(permissions[0], Manifest.permission.ACCESS_FINE_LOCATION)) {
                        if (showRequestPermission) {
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0);
                        }
                    } else {
                        if (showRequestPermission) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            //        Uri uri = Uri.fromParts("package", context.getPackageName());
                            //        intent.setData(uri);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivity(intent);
                        }
                    }
                }
                break;
            case MY_PERMISSIONS_MORE:
                for (int i = 0; i < grantResults.length; i++) {

                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //判断是否勾选禁止后不再询问
                        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
                        if (TextUtils.equals(permissions[i], Manifest.permission.ACCESS_FINE_LOCATION)) {
                            if (showRequestPermission) {
                                Intent intent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivityForResult(intent, 0);
                            }
                        } else {
                            if (showRequestPermission) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                //        Uri uri = Uri.fromParts("package", context.getPackageName());
                                //        intent.setData(uri);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                startActivity(intent);
                            }
                        }
                    } else {

                        //TODO：已经有了权限了
                        chekeHavePermission(permissions[i]);
                    }
                }

                break;

                default:
                    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                    break;
        }

    }
    private void chekeHavePermission(String permision){

        //有内存卡读取权限了
        if (TextUtils.equals(permision,Manifest.permission.READ_EXTERNAL_STORAGE)||TextUtils.equals(permision,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            havePermis();
        }

        if (TextUtils.equals(permision,Manifest.permission.CAMERA)){
            haveReadCearm();
        }
    }

    /**
     * 读取相机的权限
     */
    public void haveReadCearm() {

    }

    /**
     *  读取内存卡权限有了
     */
    public void havePermis() {

    }
}
